package com.vogue.flowmeter.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.maning.mndialoglibrary.MProgressDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vogue.flowmeter.R;
import com.vogue.flowmeter.api.entity.ApiAuthorizeEntity;
import com.vogue.flowmeter.api.entity.ApiRecordEntity;
import com.vogue.flowmeter.api.entity.BaseResponse;
import com.vogue.flowmeter.api.retrofit.NetWorkManager;
import com.vogue.flowmeter.util.AppUtils;
import com.vogue.flowmeter.util.DeviceIdUtil;
import com.vogue.flowmeter.util.NetworkUtils;
import com.vogue.flowmeter.util.PrefsUtils;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 启动页
 */
public class SplashScreenActivity extends AppCompatActivity {

    private static final int DURATION = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        RxPermissions rxPermissions=new RxPermissions(this);
        rxPermissions.request(Manifest.permission.INTERNET,Manifest.permission.READ_PHONE_STATE).subscribe(granted -> {
            if (granted){

                String deviceId= DeviceIdUtil.getDeviceId(SplashScreenActivity.this);
                PrefsUtils.getInstance(SplashScreenActivity.this).put("deviceId",deviceId);
                startUp();

                new Handler().postDelayed(() -> {
                    checkRegisterAndAuthorize();
                }, DURATION);
            }else {
                new AlertDialog.Builder(this)
                        .setTitle("操作提示")
                        .setMessage("您拒绝了应用授权，我们无法为你提供服务，点击确定关闭应用")
                        .setPositiveButton("确定", (dialog, which) -> {
                            finish();
                        });
            }
        });
    }

    private void startUp(){
        Log.e("SplashScreenActivity", "startUp");
        ApiRecordEntity apiRecord=new ApiRecordEntity();
        apiRecord.setCreateTime(new Date().getTime());
        apiRecord.setData("启动APP");
        apiRecord.setOperationName("启动APP");
        String deviceId= PrefsUtils.getInstance(SplashScreenActivity.this).get("deviceId","");
        if(TextUtils.isEmpty(deviceId)){
            return;
        }
        apiRecord.setDeviceId(deviceId);
        Log.e("SplashScreenActivity", deviceId);
        NetWorkManager
                .getInstance()
                .getBleApiService()
                .saveRecord(apiRecord)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse response) {
                        Log.e(SplashScreenActivity.class.getName(),response.getMsg());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(SplashScreenActivity.class.getName(),e.getMessage());
                        showToast("onError: "+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
    /**
     * 校验注册和授权
     */
    private void checkRegisterAndAuthorize() {
        boolean register= PrefsUtils.getInstance(SplashScreenActivity.this).get("register",false);
        //判断设备是否注册
        if (register){
            Long startTime= PrefsUtils.getInstance(SplashScreenActivity.this).get("startTime",0);
            Long endTime= PrefsUtils.getInstance(SplashScreenActivity.this).get("endTime",0);
            String authorize= PrefsUtils.getInstance(SplashScreenActivity.this).get("authorize","authorize_01");
            //判断授权时间区间和授权状态
            if (isEffectiveDate(new Date(),new Date(startTime),new Date(endTime))&&authorize.equals("authorize_02")){
                toMainHandler();
            }else {
                if (NetworkUtils.isConnected(SplashScreenActivity.this)){
                    authorize();
                }else {
                    new AlertDialog.Builder(this)
                            .setTitle("温馨提示")
                            .setMessage("您的设备需要连接网络校验授权，请确保设备已经联网")
                            .setPositiveButton("确定", (dialog, which) -> {
                                finish();
                            });
                }

            }
        }else {
            if (NetworkUtils.isConnected(SplashScreenActivity.this)){
                register();
            }else {
                new AlertDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage("您的设备没有注册过，连接网络注册设备并在后台审核之后方可使用【注：联网启动APP会自动注册设备】")
                        .setPositiveButton("确定", (dialog, which) -> {
                            finish();
                        });
            }

        }
    }

    /**
     * 注册设备
     */
    private void register() {
        Log.e("SplashScreenActivity","register");
        ApiAuthorizeEntity authorize=new ApiAuthorizeEntity();
        authorize.setDeviceId(DeviceIdUtil.getDeviceId(this));
        authorize.setAppVersion(AppUtils.getVersionName(this));
        authorize.setOsVersion(AppUtils.getVersionRelease());
        Log.e("SplashScreenActivity",""+authorize.toString());
        NetWorkManager
                .getInstance()
                .getBleApiService()
                .register(authorize)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    MProgressDialog.showProgress(SplashScreenActivity.this, "加载中...");
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        MProgressDialog.dismissProgress();
                        try {
                            String body=response.string();
                            BaseResponse res= JSON.parseObject(body,BaseResponse.class);
                            if (res.getCode()==0){
                                PrefsUtils.getInstance(SplashScreenActivity.this).put("register",true);
                                toUnauthorizedHandler();
                            }
                        }catch (IOException i){

                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(SplashScreenActivity.class.getName(),e.getMessage());
                        MProgressDialog.dismissProgress();
                        showToast("onError: "+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        MProgressDialog.dismissProgress();
                    }
                });

    }

    /**
     * 查询授权
     */
    private void authorize() {
        Log.e("SplashScreenActivity","authorize");
        ApiAuthorizeEntity authorize=new ApiAuthorizeEntity();
        authorize.setDeviceId(DeviceIdUtil.getDeviceId(this));
        Log.e("SplashScreenActivity",""+authorize.toString());
        NetWorkManager
                .getInstance()
                .getBleApiService()
                .getAuthorization(authorize)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    MProgressDialog.showProgress(SplashScreenActivity.this, "加载中...");
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        try {
                            String body=response.string();
                            BaseResponse<ApiAuthorizeEntity> res= JSON.parseObject(body,new TypeReference<BaseResponse<ApiAuthorizeEntity>>(ApiAuthorizeEntity.class){});
                            if (res.getCode()==0&&res.getData()!=null){
                                if ("authorize_02".equals(res.getData().getStatus())){
                                    PrefsUtils.getInstance(SplashScreenActivity.this).put("startTime",res.getData().getEmpowerStartTime().getTime());
                                    PrefsUtils.getInstance(SplashScreenActivity.this).put("endTime",res.getData().getEmpowerEndTime().getTime());
                                    PrefsUtils.getInstance(SplashScreenActivity.this).put("authorize",res.getData().getStatus());
                                    PrefsUtils.getInstance(SplashScreenActivity.this).put("phone",res.getData().getPhone()==null? "没有电话号码":res.getData().getPhone());
                                    toMainHandler();
                                }else {
                                    toUnauthorizedHandler();
                                }
                            }else {
                                showToast(res.getMsg());
                            }
                        }catch (IOException i){
                            showToast(i.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        MProgressDialog.dismissProgress();
                        showToast("onError: "+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        MProgressDialog.dismissProgress();
                    }
                });

    }

    /**
     * 进入首页
     */
    private void toMainHandler() {
        final Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(intent);
        finish();
    }

    /**
     * 进入未授权也
     */
    private void toUnauthorizedHandler() {
        final Intent intent = new Intent(SplashScreenActivity.this, UnauthorizedActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(intent);
        finish();
    }
    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param nowTime 当前时间
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {

        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onBackPressed() {
        // We don't want the splash screen to be interrupted
    }
    /**
     * @param msg
     */
    protected void showToast(String msg) {
        if (true) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SplashScreenActivity.this, msg, Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}